<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
// jhaosui
use addons\cms\model\Archives as ArchivesModel;
use addons\cms\model\Archives;
use app\index\model\Channel as ChannelModel;
use addons\cms\model\Modelx;
//end
/**
 * 会员中心
 */
class News extends Frontend
{
	protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }
public function article()
    {
        $action = $this->request->post("action");
        if ($action && $this->request->isPost()) {
            return $this->$action();
        }
        $diyname = $this->request->param('diyname');
        if ($diyname && !is_numeric($diyname)) {
            $archives = ArchivesModel::getByDiyname($diyname);
        } else {
            $id = $diyname ? $diyname : $this->request->param('id', '');
            $archives = ArchivesModel::get($id, ['channel']);
        }
        if (!$archives || ($archives['user_id'] != $this->auth->id && $archives['status'] != 'normal') || $archives['deletetime']) {
            $this->error(__('No specified article found'));
        }
        $channel = Channel::get($archives['channel_id']);
        if (!$channel) {
            $this->error(__('No specified channel found'));
        }
        $model = Modelx::get($channel['model_id'], [], true);
        if (!$model) {
            $this->error(__('No specified model found'));
        }
        $addon = db($model['table'])->where('id', $archives['id'])->find();
        if ($addon) {
            if ($model->fields) {
                $fieldsContentList = $model->getFieldsContentList($model->id);
                //附加列表字段
                array_walk($fieldsContentList, function ($content, $field) use (&$addon) {
                    $addon[$field . '_text'] = isset($content[$addon[$field]]) ? $content[$addon[$field]] : $addon[$field];
                });
            }
            $archives->setData($addon);
        } else {
            $this->error('No specified addon article found');
        }
        $archives->setInc("views", 1);
        $this->view->assign("__ARCHIVES__", $archives);
        $this->view->assign("__CHANNEL__", $channel);
        Config::set('cms.title', $archives['title']);
        Config::set('cms.keywords', $archives['keywords']);
        Config::set('cms.description', $archives['description']);
        // $template = preg_replace('/\.html$/', '', $channel['showtpl']);
        // return $this->view->fetch('/' . $template);
		return $this->view->fetch();
    }

    /**
     * 赞与踩
     */
    public function vote()
    {
        $id = (int)$this->request->post("id");
        $type = trim($this->request->post("type", ""));
        if (!$id || !$type) {
            $this->error(__('Operation failed'));
        }
        $archives = ArchivesModel::get($id);
        if (!$archives || ($archives['user_id'] != $this->auth->id && $archives['status'] != 'normal') || $archives['deletetime']) {
            $this->error(__('No specified article found'));
        }
        $archives->where('id', $id)->setInc($type === 'like' ? 'likes' : 'dislikes', 1);
        $archives = ArchivesModel::get($id);
        $this->success(__('Operation completed'), null, ['likes' => $archives->likes, 'dislikes' => $archives->dislikes, 'likeratio' => $archives->likeratio]);
    }
    /**
     * 会员中心
     */
    public function index()
    {
		$diyname = $this->request->param('diyname');
		
		if ($diyname && !is_numeric($diyname)) {
		    $channel = ChannelModel::getByDiyname($diyname);
		} else {
		    $id = 2;//$diyname ? $diyname : $this->request->param('id', '');
		    $channel = ChannelModel::get($id);
		}
		if (!$channel) {
		    $this->error(__('No specified channel found'));
		}
		$channel = ChannelModel::get(5);
		$filterlist = [];
		$orderlist = [];
		
		$filter = $this->request->get('filter/a', []);
		$orderby = $this->request->get('orderby', '');
		$orderway = $this->request->get('orderway', '', 'strtolower');
		$params = ['filter' => '', 'id' => $channel->id, 'diyname' => $channel->diyname];
		if ($filter)
		    $params['filter'] = $filter;
		if ($orderby)
		    $params['orderby'] = $orderby;
		if ($orderway)
		    $params['orderway'] = $orderway;
		if ($channel['type'] === 'link') {
		    $this->redirect($channel['outlink']);
		}
		
		$model = Modelx::get($channel['model_id']);
		if (!$model) {
		    $this->error(__('No specified model found'));
		}
		$fields = [];
		foreach ($model->fields_list as $k => $v) {
		    if (!$v['isfilter'] || !in_array($v['type'], ['select', 'selects', 'checkbox', 'radio', 'array']) || !$v['content_list'])
		        continue;
		    $fields[] = [
		        'name' => $v['name'], 'title' => $v['title'], 'content' => $v['content_list']
		    ];
		}
		$filter = array_intersect_key($filter, array_flip(array_column($fields, 'name')));
		foreach ($fields as $k => $v) {
		    $content = [];
		    $all = ['' => __('All')] + $v['content'];
		    foreach ($all as $m => $n) {
		        $active = ($m === '' && !isset($filter[$v['name']])) || (isset($filter[$v['name']]) && $filter[$v['name']] == $m) ? TRUE : FALSE;
		        $prepare = $m === '' ? array_diff_key($filter, [$v['name'] => $m]) : array_merge($filter, [$v['name'] => $m]);
		        $url = '?' . http_build_query(array_merge(['filter' => $prepare], array_diff_key($params, ['filter' => ''])));
		        $content[] = ['value' => $m, 'title' => $n, 'active' => $active, 'url' => $url];
		    }
		    $filterlist[] = [
		        'name'    => $v['name'],
		        'title'   => $v['title'],
		        'content' => $content,
		    ];
		}
		
		$sortrank = [
		    ['name' => 'default', 'field' => 'weigh', 'title' => __('Default')],
		    ['name' => 'views', 'field' => 'views', 'title' => __('Views')],
		    ['name' => 'id', 'field' => 'id', 'title' => __('Post date')],
		];
		
		$orderby = $orderby && in_array($orderby, ['default', 'id', 'views']) ? $orderby : 'default';
		$orderway = $orderway ? $orderway : 'desc';
		foreach ($sortrank as $k => $v) {
		    $url = '?' . http_build_query(array_merge($params, ['orderby' => $v['name'], 'orderway' => ($orderway == 'desc' ? 'asc' : 'desc')]));
		    $v['active'] = $orderby == $v['name'] ? true : false;
		    $v['orderby'] = $orderway;
		    $v['url'] = $url;
		    $orderlist[] = $v;
		}
		$orderby = $orderby == 'default' ? 'weigh' : $orderby;
		$pagelist = Archives::alias('a')
		    ->where('status', 'normal')
		    ->where('deletetime', 'exp', \think\Db::raw('IS NULL'))
		    ->where($filter)
		    ->join($model['table'] . ' n', 'a.id=n.id', 'LEFT')
		    ->field('a.*')
		    ->field('id,content', true, config('database.prefix') . $model['table'], 'n')
		    ->where('channel_id', $channel['id'])
		    ->order($orderby, $orderway)
		    ->paginate($channel['pagesize'], false, ['type' => '\\addons\\cms\\library\\Bootstrap']);
		$pagelist->appends($params);
		$this->view->assign("__FILTERLIST__", $filterlist);
		$this->view->assign("__ORDERLIST__", $orderlist);
		$this->view->assign("__PAGELIST__", $pagelist);
		$this->view->assign("__CHANNEL__", $channel);
		Config::set('cms.title', $channel['name']);
		Config::set('cms.keywords', $channel['keywords']);
		Config::set('cms.description', $channel['description']);
		$template = preg_replace('/\.html$/', '', $channel["{$channel['type']}tpl"]);
        $this->view->assign('title', __('User center'));
        return $this->view->fetch();
    }
	public function local()
	{
		$diyname = $this->request->param('diyname');
		
		if ($diyname && !is_numeric($diyname)) {
		    $channel = ChannelModel::getByDiyname($diyname);
		} else {
		    $id = 2;//$diyname ? $diyname : $this->request->param('id', '');
		    $channel = ChannelModel::get($id);
		}
		if (!$channel) {
		    $this->error(__('No specified channel found'));
		}
		$channel = ChannelModel::get(5);
		$filterlist = [];
		$orderlist = [];
		
		$filter = $this->request->get('filter/a', []);
		$orderby = $this->request->get('orderby', '');
		$orderway = $this->request->get('orderway', '', 'strtolower');
		$params = ['filter' => '', 'id' => $channel->id, 'diyname' => $channel->diyname];
		if ($filter)
		    $params['filter'] = $filter;
		if ($orderby)
		    $params['orderby'] = $orderby;
		if ($orderway)
		    $params['orderway'] = $orderway;
		if ($channel['type'] === 'link') {
		    $this->redirect($channel['outlink']);
		}
		
		$model = Modelx::get($channel['model_id']);
		if (!$model) {
		    $this->error(__('No specified model found'));
		}
		$fields = [];
		foreach ($model->fields_list as $k => $v) {
		    if (!$v['isfilter'] || !in_array($v['type'], ['select', 'selects', 'checkbox', 'radio', 'array']) || !$v['content_list'])
		        continue;
		    $fields[] = [
		        'name' => $v['name'], 'title' => $v['title'], 'content' => $v['content_list']
		    ];
		}
		$filter = array_intersect_key($filter, array_flip(array_column($fields, 'name')));
		foreach ($fields as $k => $v) {
		    $content = [];
		    $all = ['' => __('All')] + $v['content'];
		    foreach ($all as $m => $n) {
		        $active = ($m === '' && !isset($filter[$v['name']])) || (isset($filter[$v['name']]) && $filter[$v['name']] == $m) ? TRUE : FALSE;
		        $prepare = $m === '' ? array_diff_key($filter, [$v['name'] => $m]) : array_merge($filter, [$v['name'] => $m]);
		        $url = '?' . http_build_query(array_merge(['filter' => $prepare], array_diff_key($params, ['filter' => ''])));
		        $content[] = ['value' => $m, 'title' => $n, 'active' => $active, 'url' => $url];
		    }
		    $filterlist[] = [
		        'name'    => $v['name'],
		        'title'   => $v['title'],
		        'content' => $content,
		    ];
		}
		
		$sortrank = [
		    ['name' => 'default', 'field' => 'weigh', 'title' => __('Default')],
		    ['name' => 'views', 'field' => 'views', 'title' => __('Views')],
		    ['name' => 'id', 'field' => 'id', 'title' => __('Post date')],
		];
		
		$orderby = $orderby && in_array($orderby, ['default', 'id', 'views']) ? $orderby : 'default';
		$orderway = $orderway ? $orderway : 'desc';
		foreach ($sortrank as $k => $v) {
		    $url = '?' . http_build_query(array_merge($params, ['orderby' => $v['name'], 'orderway' => ($orderway == 'desc' ? 'asc' : 'desc')]));
		    $v['active'] = $orderby == $v['name'] ? true : false;
		    $v['orderby'] = $orderway;
		    $v['url'] = $url;
		    $orderlist[] = $v;
		}
		$orderby = $orderby == 'default' ? 'weigh' : $orderby;
		$pagelist = Archives::alias('a')
		    ->where('status', 'normal')
		    ->where('deletetime', 'exp', \think\Db::raw('IS NULL'))
		    ->where($filter)
		    ->join($model['table'] . ' n', 'a.id=n.id', 'LEFT')
		    ->field('a.*')
		    ->field('id,content', true, config('database.prefix') . $model['table'], 'n')
		    ->where('channel_id', $channel['id'])
		    ->order($orderby, $orderway)
		    ->paginate($channel['pagesize'], false, ['type' => '\\addons\\cms\\library\\Bootstrap']);
		$pagelist->appends($params);
		$this->view->assign("__FILTERLIST__", $filterlist);
		$this->view->assign("__ORDERLIST__", $orderlist);
		$this->view->assign("__PAGELIST__", $pagelist);
		$this->view->assign("__CHANNEL__", $channel);
		Config::set('cms.title', $channel['name']);
		Config::set('cms.keywords', $channel['keywords']);
		Config::set('cms.description', $channel['description']);
		$template = preg_replace('/\.html$/', '', $channel["{$channel['type']}tpl"]);
	    $this->view->assign('title', __('User center'));
	    return $this->view->fetch();
	}

    
}
